package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    private final CategoryBrandService categoryBrandService;

    public BrandServiceImpl(CategoryBrandService categoryBrandService) {
        this.categoryBrandService = categoryBrandService;
    }

    @Override
    public List<BrandDTO> queryBrandByCategory(Long categoryId) {
        // 查询品牌
        List<Brand> list = getBaseMapper().queryBrandByCategoryId(categoryId);
        // 转换DTO
        return BrandDTO.convertEntityList(list);
    }

    @Override
    public PageDTO<BrandDTO> queryBrandByPage(String key, Integer page, Integer rows) {
        // 查询
        Page<Brand> result = query()
                // WHERE `name` LIKE "%x%"
                .like(StringUtils.isNotBlank(key), "name", key)
                // OR
                .or()
                // letter = "x"
                .eq(StringUtils.isNotBlank(key), "letter", key)
                // LIMIT 0,5
                .page(new Page<>(page, rows));
        // 解析结果
        long total = result.getTotal();
        long totalPage = result.getPages();
        List<Brand> list = result.getRecords();
        // 转换DTO
        List<BrandDTO> items = BrandDTO.convertEntityList(list);
        // 封装返回
        return new PageDTO<>(total, totalPage, items);
    }

    @Transactional
    @Override
    public void saveBrand(BrandDTO brandDTO) {
        // DTO转换po
        Brand brand = brandDTO.toEntity(Brand.class);
        // 新增品牌数据
        save(brand);

        // 获取品牌id
        Long brandId = brand.getId();
        // 获取分类id集合
        List<Long> categoryIds = brandDTO.getCategoryIds();
        // 组织中间表对象集合
        List<CategoryBrand> cbList = categoryIds.stream()
                .map(categoryId -> CategoryBrand.of(categoryId, brandId))
                .collect(Collectors.toList());
        // 新增中间表数据
        categoryBrandService.saveBatch(cbList);
    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        // 1.更新品牌
        boolean success = updateById(brandDTO.toEntity(Brand.class));
        if (!success) {
            // 更新失败，抛出异常
            throw new LyException(500, "更新品牌失败！");
        }
        // 2.根据品牌id删除中间表数据
        success = categoryBrandService.remove(
                new QueryWrapper<CategoryBrand>().eq("brand_id", brandDTO.getId()));
        if (!success) {
            // 更新失败，抛出异常
            throw new LyException(500,"更新品牌失败，删除中间表数据出错");
        }
        // 3.重新插入中间表数据
        List<CategoryBrand> list = brandDTO.getCategoryIds().stream()
                .map(id -> CategoryBrand.of(id, brandDTO.getId()))
                .collect(Collectors.toList());
        // 批量写入中间表数据
        categoryBrandService.saveBatch(list);
    }
}
